<HTML>
<HEAD>
<TITLE>Example Program: Exceptions</TITLE>
<LINK REL=StyleSheet HREF="../rw.css" TYPE="text/css" TITLE="Rogue Wave Standard Stylesheet"></HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="18-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="VI.html"><IMG SRC="images/bnext.gif" WIDTH=25 HEIGHT=21 ALT="Next file" BORDER=O></A><DIV CLASS="DOCUMENTNAME"><B>Rogue Wave C++ Standard Library User's Guide</B></DIV>
<H2>18.4 Example Program: Exceptions</H2>
<BLOCKQUOTE><HR><B>
NOTE -- This program is in the file exceptn.cpp.
</B><HR></BLOCKQUOTE>
<A NAME="idx428"><!></A>
<P>This following example program demonstrates the use of exceptions:</P>

<UL><PRE>
#include &lt;stdexcept&gt;
#include &lt;string&gt;

static void f() { throw std::runtime_error("a runtime error"); }

int main ()
{
  std::string s;
  
  // First we'll try to incite then catch an exception 
  // from the Standard C++ Library string class.
  // We'll try to replace at a position that is non-existent.
  //
  // By wrapping the body of main in a try-catch block we can be
  // assured that we'll catch all exceptions in the exception
  // hierarchy. You can simply catch an exception as is done 
  // below, or you can catch each of the exceptions in which 
  // you have an interest.
  try
  {
    s.replace(100,1,1,'c');
  }
  catch (const std::exception&amp; e)
  {
    std::cout &lt;&lt; "Got an exception: " &lt;&lt; e.what() &lt;&lt; std::endl;
  }

  // Now we'll throw our own exception using the function 
  // defined above.
  try
  {
    f();
  }
  catch (const std::exception&amp; e)
  {
    std::cout &lt;&lt; "Got an exception: " &lt;&lt; e.what() &lt;&lt; std::endl;
  }
 
  return 0;
}
</PRE></UL>


<BR>
<HR>
<A HREF="18-3.html"><IMG SRC="images/bprev.gif" WIDTH=20 HEIGHT=21 ALT="Previous file" BORDER=O></A><A HREF="noframes.html"><IMG SRC="images/btop.gif" WIDTH=56 HEIGHT=21 ALT="Top of Document" BORDER=O></A><A HREF="booktoc.html"><IMG SRC="images/btoc.gif" WIDTH=56 HEIGHT=21 ALT="Contents" BORDER=O></A><A HREF="tindex.html"><IMG SRC="images/bindex.gif" WIDTH=56 HEIGHT=21 ALT="Index page" BORDER=O></A><A HREF="VI.html"><IMG SRC="images/bnext.gif" WIDTH=20 HEIGHT=21 ALT="Next file" BORDER=O></A></BODY>
</HTML>
